<?php
/**
 * Copyright 2011 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

require 'FBsdk/src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '384457058286773',
  'secret' => '91cb5c207e8ad2a779ffd14d5e563194',
));

// Get User ID
$user = $facebook->getUser();

// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user)
{
  $logoutUrl = $facebook->getLogoutUrl();
  
  $posts = idx($facebook->api('/me/posts?limit=20'), 'data', array());
  //$posts = idx($facebook->api('/me/posts?limit=20'), 'data', array());
}
else
{
  $loginUrl = $facebook->getLoginUrl(  );
  //<a href="https://www.facebook.com/dialog/oauth?client_id=384457058286773&amp;redirect_uri=http%3A%2F%2Fbespoke-app.com%2FbeSpokeAPI%2FFacebook%2F&amp;state=ca91952668891d64d6cf490f6a7ad5ed">Login with Facebook</a>
  
// Connect to SQL Server to Get UserAccount
//require_once 'mysql_connect.php';

//$strCommand = "SELECT * FROM Organization WHERE idOrganization = 0";
//$result = mysql_query($strSqlCommand);
//$rowAccount = @mysql_fetch_array($result);	
}

// This call will always work since we are fetching public data.
$naitik = $facebook->api('/naitik');


if ($user)
{

	$i = 0;
	foreach ($posts as $post)
	{
		// Extract the pieces of info we need from the requests above
		echo "<div>";
		echo "ID : ".$post['id'] . "<br/>";
		echo "from : ". $post['from']['name'] . "<br/>";
		echo "message : ". $post ['message'] . "<br/>";
		echo "updated_time : ". $post ['updated_time'] . "<br/>";
		echo "</div>";	
	}
} 
else
{
	header('Location: '.$loginUrl);
}
   
	function idx(array $array, $key, $default = null) {
		return array_key_exists($key, $array) ? $array[$key] : $default;
	}       
?>